#include "ConfigManager.h"
#include "tinyxml.h"

ConfigManager * ConfigManager::sInstance = NULL;

ConfigManager::ConfigManager()
{

}

ConfigManager::~ConfigManager()
{
	for( ConfigTable::iterator it = m_configTable.begin(); it != m_configTable.end(); ++it )
	{
		CC_SAFE_RELEASE( it->second );
	}
	m_configTable.clear();
}

ConfigManager * ConfigManager::createConfigManager()
{
	ConfigManager * ret = new ConfigManager();
	if( ret && ret->init())
	{
		ret->autorelease();
		return ret;
	}

	CC_SAFE_DELETE(ret);
	return NULL;
}

ConfigManager *	ConfigManager::instance()
{
	if( sInstance == NULL )
	{
		sInstance = createConfigManager();
		sInstance->retain();
	}
	return sInstance;
}


bool ConfigManager::init()
{
	bool ret = true;
	TiXmlDocument * doc = new TiXmlDocument();

	if( doc->LoadFile("xml/main.xml") )
	{
		TiXmlElement * elem = doc->RootElement()->FirstChildElement();
		elem = elem->NextSiblingElement("configs");
		Config * config = Config::configWithXml(elem);

		if( config )
		{
			Config::DataTable::iterator it	= config->getItems().begin();
			Config::DataTable::iterator end = config->getItems().end();
			for( ; it != end ; ++it )
			{
				const string&		key			= it->first;
				Config::DataItem&	item		= it->second;
				const string&		path		= item["path"];

				Config * db = Config::configWithFile(path.c_str());
				db->retain();
#ifdef USE_CRC
				m_configTable.insert(make_pair( AGCrc::calculate(key.c_str()), db ));
#else
				m_configTable.insert(make_pair( key, db ));
#endif

			}
		}

		config->release();

	}else
	{
		ret = false;
	}
	CC_SAFE_DELETE(doc);
	return ret;
}

Config* ConfigManager::getConfig( const char * name )
{
#ifdef USE_CRC
	int key = AGCrc::calculate(name);
#else
	const char * key = name;
#endif

	if( m_configTable.find(key)!= m_configTable.end() )
	{
		return m_configTable[key];
	}
	return NULL;
}